// pages/home/index.js
var app = getApp();

var page_index = 0;
var page_size = 20;
var page_refresh = false;
var page_timer = null;
var page_total=20;
var query_size = 20;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    hidden: true,
    list_device: [],
    select_did: "",
    touchStartTime: 0,          // 触摸开始时间
    touchEndTime: 0,            // 触摸结束时间
    lastTapTime: 0,             // 最后一次单击事件点击发生时间
    lastTapTimeoutFunc: null,   // 单击事件点击后要触发的函数
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    page_timer = null;
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var token = wx.getStorageSync('Token')//app.globalData.Token;
    //console.log("Index:" + token);
    if (token == null || token == "") {
      wx.navigateTo({
        url: '/pages/user/login'
      })
      return;
    }
    else {
      app.globalData.Token = token;
      app.globalData.userInfo = wx.getStorageSync('User');
    }

    page_timer = null;
    page_refresh = true;
    this.refresh();
    this.ontimer();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    page_refresh = false;
    page_timer = null;
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    page_refresh = false;
    page_timer = null;
  },
  //请求数据
  refresh: function (e) {
    //  该方法绑定了页面滑动到顶部的事件，然后做上拉刷新
    var that = this;
    var token = app.globalData.Token;
    if (token == null || token == "") return;
    wx.request({
      url: app.globalData.Url + "Api/Device/GetMyDevice", //仅为示例，并非真实的接口地址
      data: {
        token: token,
        index: page_index,
        size: query_size
      },
      header: { 'content-type': 'application/json' },
      success: function (res) {
        //console.log(res.data);
        if(res.data.result)
        {
          that.setData({ list_device: res.data.data });
          page_total = res.data.data.length;
          //console.log("page_total:"+page_total);
        }        
      }
    })
  },
  //定时方法
  ontimer: function () {
    var that = this;
    page_timer = setTimeout(function () {
      //console.log("----ontimer 定时器...----");
      if (page_refresh) {
        that.refresh();
        that.ontimer();
      }
    }, 10000);
  },
  onclick: function (e) {
    clearTimeout(page_timer);
    page_refresh = false;
    page_timer = null;
    //console.log(e);
    //console.log("did:" + e.currentTarget.dataset.did);
    wx.navigateTo({
      url: '/pages/home/device/nh301?did=' + e.currentTarget.dataset.did
    })
  },
  //按钮触摸开始触发的事件
  touchStart: function (e) {
    this.touchStartTime = e.timeStamp
  },
  //按钮触摸结束触发的事件
  touchEnd: function (e) {
    this.touchEndTime = e.timeStamp;
    this.select_did = e.currentTarget.dataset.did;
    //console.log(this.select_did);
  },
  //双击
  doubleTap: function (e) {
    var that=this;
    that.select_did = e.currentTarget.dataset.did;
    //console.log("did:" + this.select_did);
    var _type = e.currentTarget.dataset.type;
    var p = this.getdevicetype(_type)
    // var p = _type == "NH301" ? "nh301" : (_type == "SHT3X" ? "sht3x" : (_type == "BH1750" ? "nh301" : (_type == "ACS01" ? "acs01" : "sh027x")));
    // 控制点击事件在350ms内触发，加这层判断是为了防止长按时会触发点击事件
    if (that.touchEndTime - that.touchStartTime < 350) {
      // 当前点击的时间
      var currentTime = e.timeStamp
      var lastTapTime = that.lastTapTime
      // 更新最后一次点击时间
      that.lastTapTime = currentTime

      // 如果两次点击时间在300毫秒内，则认为是双击事件
      if (currentTime - lastTapTime < 300) {
        //console.log("double tap")
        // 成功触发双击事件时，取消单击事件的执行
        //clearTimeout(that.onclick);
        clearTimeout(page_timer);
        page_refresh = false;
        page_timer = null;
        wx.navigateTo({
          url: '/pages/home/device?did=' + that.select_did + '&type=' + _type
        })
      }
    }
  },
  getdevicetype: function (_type) {
    var rs = "nh301";
    switch (_type) {
      case "GAS01":
      case "LUX01":
      case "BH1750":
      case "NH301": rs = "nh301"; break;
      case "SHT3X": rs = "sht3x"; break;
      case "ACS02":
      case "ACS01": rs = "acs01"; break;
      case "0271":
      case "0272":
      case "0273": rs = "sh027x"; break;
      case "VD01": rs = "vd01"; break;
      case "FC01": rs = "fc01"; break;
    }
    return rs;
  },
  //控制指令
  devicecmd: function (e) {
    var v = e.currentTarget.dataset.v;
    var value = e.currentTarget.dataset.value;
    //console.log("did:" + this.select_did);
    var that = this;

    var token = app.globalData.Token;
    if (token == null || token == "") return;
    var start = 1;
    var value = value == 1 ? "00" : "01";
    var c = {};
    var d = {};
    d.start = v == "V" ? 1 : (v == "V2" ? 2 : (v == "V3" ? 3 : 1));
    d.data = value;
    c.action = "Device/Write";
    c.args = d;
    var cmd = JSON.stringify(c);
    wx.request({
      url: app.globalData.Url + "Api/Device/DeviceCommand", //仅为示例，并非真实的接口地址
      data: {
        token: token,
        did: that.select_did,
        cmd: cmd,
      },
      header: { 'content-type': 'application/json' },
      success: function (res) {
        var msg = "";
        if (res.data.result) {
          setTimeout(that.refresh,500);
        }
        else {
          wx.showToast({
            title: res.data.data,
            icon: 'none',
            duration: 1000
          })
        }
      }
    })
  },
  //控制指令
  fccmd: function (e) {
    var value = e.detail.value;
    var that = this;

    var token = app.globalData.Token;
    if (token == null || token == "") return;

    var c = {};
    var d = {};
    d.State = 1;
    d.Rate = value;

    c.action = "SetOperate";
    c.args = d;
    var cmd = JSON.stringify(c);
    //console.log("cmd:" + cmd);
    wx.request({
      url: app.globalData.Url + "Api/Device/DeviceCommand", //仅为示例，并非真实的接口地址
      data: {
        token: token,
        did: that.select_did,
        cmd: cmd,
      },
      header: { 'content-type': 'application/json' },
      success: function (res) {
        var msg = "";
        if (res.data.result) {
          //setTimeout(that.refresh, 15000);
        }
        else {
          wx.showToast({
            title: res.data.data,
            icon: 'none',
            duration: 1000
          })
        }
      }
    })
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.data.hidden=false;
    //console.log("上拉触底事件");
    if (page_total >= query_size) {
      query_size = query_size + page_size;
    }
    //console.log("page_total:" + page_total + " page_size:" + query_size);
    this.refresh();
  },
})